package com.jiujichina.star.consumer;

import com.jiujichina.star.config.KafkaConsumerConfig;
import com.jiujichina.star.producer.KafkaProducerDemo;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 生产者
 * 使用@EnableScheduling注解开启定时任务
 */
@Component
public class KafkaConsumerDemo implements CommandLineRunner {

    Logger logger = LoggerFactory.getLogger(KafkaConsumerDemo.class);

    @Autowired
    private  KafkaConsumer consumer;

    private final AtomicBoolean closed = new AtomicBoolean(false);

    public void consumerMsg(){
        try {
            consumer.subscribe(Arrays.asList("test"));
            while (!closed.get()) {
                ConsumerRecords<String,Object> records = consumer.poll(10000);
                // Handle new records
                for (TopicPartition partition : records.partitions()) {
                    List<ConsumerRecord<String, Object>> partitionRecords = records.records(partition);
                    for (ConsumerRecord<String, Object> record : partitionRecords) {
                        String value =  (String)record.value();
                        logger.info("接收到的消息{},分区{}",value,partition.toString());
                    }
                }
            }
        } catch (WakeupException e) {
            // Ignore exception if closing
            if (!closed.get()) throw e;
        } finally {
            consumer.close();
        }
    }

    @Override
    public void run(String... strings) throws Exception {
            new Thread(() -> {
                consumerMsg();
            }).start();
    }

}
